package com.tikeyc.flutterandroid.custom;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.tikeyc.flutterandroid.BuildConfig;

import io.flutter.Log;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodCodec;

/*MethodChannel是最常用的Native和Flutter的通信方式
 *主要用于Flutter调用Native端方法，如调用Native相机功能
* */
public class MyMethodChannel extends MethodChannel {
    public static final String Method_Channel = "com.tikeyc.fluttermodule/methodChannel";

    public MyMethodChannel(@NonNull BinaryMessenger messenger, @NonNull String name) {
        super(messenger, name);
    }

    public MyMethodChannel(@NonNull BinaryMessenger messenger, @NonNull String name, @NonNull MethodCodec codec) {
        super(messenger, name, codec);
    }

    public MyMethodChannel(@NonNull BinaryMessenger messenger, @NonNull String name, @NonNull MethodCodec codec, @Nullable BinaryMessenger.TaskQueue taskQueue) {
        super(messenger, name, codec, taskQueue);
    }

    public static MyMethodChannel instance(FlutterEngine flutterEngine) {
        MyMethodChannel myMethodChannel = new MyMethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), Method_Channel);
        return myMethodChannel;
    }

    public static MyMethodChannel instance(FlutterEngine flutterEngine, String name) {
        MyMethodChannel myMethodChannel = new MyMethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), name);
        return myMethodChannel;
    }

    public MyMethodChannel initMethod() {
        setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
                //判断调用的方法名
                if(call.method.equals("testMethodCall")) {
                    //获取传递的参数
                    Log.e("test", "Have received Test Method Call :${call.arguments}");
                    //返回结果给Flutter端
                    result.success(BuildConfig.DEBUG + " " +"yes");
                }
            }
        });
        return this;
    }
}
